/**
 * 测试环境 请求的地址配置
 *
 * @flow
 */

import React, { Component } from 'react'
import {
  StyleSheet,
  View,
  Text,
  Button,
  FlatList,
  Keyboard,
  TouchableOpacity,
} from 'react-native'

import store from 'react-native-simple-store'
import * as DevUtil from '../utils/devEnv'
import RXEmitter from 'react-native-rxemitter'

export const devEnvironmentList = [
  {
    betaName: '自定义',
    baseUrl: '',
  },
  {
    betaName: 'betaA',
    baseUrl: 'http://baidu.com',
  },
  {
    betaName: 'betaB',
    baseUrl: 'http://google.com',
  },
]

export default class SwithDns extends Component {
  static navigationOptions = ({ navigation, route }) => ({
    headerRight: () => (
      <Button
        title={'保存'}
        onPress={(e) => {
          RXEmitter.emit('edit_save')
        }}
      />
    ),
  })

  constructor(props) {
    super(props)
    this.state = {
      currentValue: '',

      selectIndex: -1,
      selectTitle: '',
      selectValue: '',

      diyValue: '',
    }
  }

  componentDidMount() {
    RXEmitter.addListener(this, 'edit_save', this._save)
    this.getUrl(true)
  }

  componentWillUnmount() {
    RXEmitter.removeLister(this, 'edit_save')
  }

  getUrl(autoSelect = false) {
    DevUtil.getDevBaseUrl().then(baseUrl => {
      // console.log('getDevBaseUrl', baseUrl)
      this.setState({ currentValue: baseUrl })
      let { selectIndex, selectTitle, selectValue } = this.state
      this.getDiyUrl().then(url => {
        // console.log('diyValue=' + url)
        if (autoSelect) {
          let loopUp = true
          devEnvironmentList.forEach((item, index) => {
            const tbetaName = item.betaName
            const tbaseUrl = item.baseUrl
            if (baseUrl === tbaseUrl) {
              selectValue = baseUrl
              selectIndex = index
              selectTitle = tbetaName
              loopUp = false
              return null
            }
          })

          if (loopUp && url === baseUrl) {
            selectTitle = '自定义'
            selectValue = url
            selectIndex = 0
          } else if (loopUp) {
            selectTitle = 'unkonw'
            selectValue = 'unkonw'
          }
          this.setState({ diyValue: url, selectIndex, selectTitle, selectValue })
        } else {
          this.setState({ diyValue: url, selectValue: url, selectTitle: '自定义' })
        }
      })
    })
  }

  editSucc = () => {
    this.getUrl()
    this.setState({ selectIndex: 0 })
  }

  async getDiyUrl() {
    return await store.get('diyUrl')
  }

  _save = () => {
    const { selectIndex, selectValue, diyValue } = this.state
    if (selectIndex < 0) {
      alert('没有更改')
      return
    }

    const url = selectIndex === 0 ? diyValue : selectValue

    DevUtil.setDevBaseUrl(url)
    setTimeout(() => {
      this.getUrl(true)
    }, 10)
    alert('修改成功，需要重启app')
  }

  _renderItem = (data) => {
    const { item, index } = data
    const { diyValue, selectIndex } = this.state

    const betaName = item.betaName
    const baseUrl = index === 0 ? diyValue : item.baseUrl
    const bg = index === selectIndex ? { backgroundColor: '#FFA500' } : {}
    return (
      <TouchableOpacity
        style={[styles.listBtn, bg]}
        onPress={() => {
          Keyboard.dismiss()
          this.setState({
            selectIndex: index,
            selectTitle: betaName,
            selectValue: baseUrl,
          })
        }}
      >
        <Text style={styles.text}>{betaName}</Text>
        <Text style={styles.text}>{baseUrl}</Text>
      </TouchableOpacity>
    )
  }

  render() {
    const { currentValue, selectTitle, selectValue } = this.state

    return (
      <View style={styles.container}>
        <View style={styles.selView}>
          <Text style={styles.selText}>{'当前-使用的`域名`'}</Text>
          <Text>{currentValue}</Text>
          <Text style={[styles.selText, { marginTop: 10 }]}>
            {'当前-选择的`域名`'}
          </Text>
          <View style={{ flexDirection: 'row', alignItems: 'center' }}>
            <Text>{selectTitle}</Text>
            <TouchableOpacity
              style={styles.selTouch}
              onPress={() => {
                const params = {
                  url: selectValue,
                  title: '编辑-' + selectTitle,
                  callback: this.editSucc,
                }
                this.props.navigation.navigate('editSwithDns', params)
              }}
            >
              <Text style={styles.selTouchTxt}>编辑</Text>
            </TouchableOpacity>
          </View>
          <Text>{selectValue}</Text>
        </View>
        <View style={{ height: 1, backgroundColor: '#00FFFF' }} />
        <FlatList
          style={{ flex: 1 }}
          data={devEnvironmentList}
          keyExtractor={(item, index) => index}
          numColumns={1}
          horizontal={false}
          // ListEmptyComponent={this._renderEmpty}
          renderItem={this._renderItem}
          // ItemSeparatorComponent={this._renderSeparator}
          keyExtractor={(item, index) => index.toString()}
          onEndReachedThreshold={0.5}
          showsVerticalScrollIndicator={false}
        />
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
  },
  selView: {
    padding: 5,
  },
  selText: {
    fontSize: 20,
  },
  selTouch: {
    marginLeft: 10,
    width: 80,
    height: 20,
    backgroundColor: 'blue',
    borderRadius: 3,
    justifyContent: 'center',
    alignItems: 'center',
  },
  selTouchTxt: {
    color: 'white',
  },
  button: {
    padding: 20,
    backgroundColor: 'blue',
    justifyContent: 'center',
    alignItems: 'center',
  },
  text: {
    lineHeight: 20,
    fontSize: 12,
    color: 'white',
  },
  listBtn: {
    marginHorizontal: 30,
    marginVertical: 10,
    borderRadius: 3,
    backgroundColor: '#008B8B',
    justifyContent: 'center',
    alignItems: 'center',
  },
})
